package com.lin.sqltool;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.LineNumberFactory;
import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyleSpansBuilder;

import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CodeEditor extends Application {

    // 定义Java关键字样式
    private static final String[] KEYWORDS = new String[]{
            "abstract", "assert", "boolean", "break", "byte",
            "case", "catch", "char", "class", "const",
            // ... 其他关键字
            "continue", "default", "do", "double", "else",
            "enum", "extends", "final", "finally", "float",
            "for", "if", "implements", "import", "instanceof",
            "int", "interface", "long", "native", "new",
            "package", "private", "protected", "public", "return",
            "short", "static", "strictfp", "super", "switch",
            "synchronized", "this", "throw", "throws", "transient",
            "try", "void", "volatile", "while"
    };

    private static final String KEYWORD_PATTERN = "\\b(" + String.join("|", KEYWORDS) + ")\\b";

    @Override
    public void start(Stage stage) {
        CodeArea codeArea = new CodeArea();

        // 设置语法高亮
        codeArea.setStyleSpans(0, computeHighlighting(codeArea.getText()));

        // 文本修改监听
        codeArea.textProperty().addListener((obs, oldText, newText) -> {
            codeArea.setStyleSpans(0, computeHighlighting(newText));
        });

        // 启用行号
        codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea));

        Scene scene = new Scene(new VirtualizedScrollPane(codeArea), 800, 600);
        // 加载 CSS 文件
        scene.getStylesheets().add(getClass().getResource("/css/code-editor.css").toExternalForm());

        stage.setScene(scene);
        stage.show();
    }

    // 高亮计算逻辑
    private StyleSpans<Collection<String>> computeHighlighting(String text) {
        StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();

            Matcher matcher = Pattern.compile(KEYWORD_PATTERN).matcher(text);
        int lastKwEnd = 0;

        while (matcher.find()) {
            // 普通文本样式
            spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd);
            // 关键字样式
            spansBuilder.add(Collections.singleton("keyword"), matcher.end() - matcher.start());
            lastKwEnd = matcher.end();
        }
        // 剩余文本
        spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd);
        return spansBuilder.create();
    }

    public static void main(String[] args) {
        launch(args);
    }
}